<template>
  <div class="salary-range">
    <el-input
      v-model="minSalary"
      placeholder="最低薪资"
      @input="handleMinInput"
      :style="{ width: width + 'px' }"
    />
    <span class="separator">-</span>
    <el-input
      v-model="maxSalary"
      placeholder="最高薪资"
      @input="handleMaxInput"
      :style="{ width: width + 'px' }"
    />
    <span class="unit">元/月</span>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  width: {
    type: Number,
    default: 120
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const minSalary = ref('')
const maxSalary = ref('')

// 处理最小值输入
const handleMinInput = (value) => {
  minSalary.value = value.replace(/[^\d]/g, '')
  handleChange()
}

// 处理最大值输入
const handleMaxInput = (value) => {
  maxSalary.value = value.replace(/[^\d]/g, '')
  handleChange()
}

// 监听外部值变化
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    const [min, max] = newVal.split('-').map(Number)
    minSalary.value = min ? min.toString() : ''
    maxSalary.value = max ? max.toString() : ''
  } else {
    minSalary.value = ''
    maxSalary.value = ''
  }
}, { immediate: true })

// 处理值变化
const handleChange = () => {
  const value = minSalary.value && maxSalary.value 
    ? `${minSalary.value}-${maxSalary.value}`
    : ''
  
  emit('update:modelValue', value)
  emit('change', value)
}
</script>

<style lang="scss" scoped>
.salary-range {
  display: flex;
  align-items: center;
  gap: 8px;

  .separator {
    color: #606266;
  }

  .unit {
    color: #909399;
    font-size: 14px;
  }
}
</style> 